using System;
using System.Reflection;
using Microsoft.SharePoint;

namespace CKS.EBE
{
	public static class SPEventManagerWrapper
	{
		private const string ClassName = "Microsoft.SharePoint.SPEventManager";
		private const string EventFiringSwitchName = "EventFiringDisabled";
		private static Type _eventManagerType;

		/// <summary>
		/// gets the status of event firing on the current thread
		/// </summary>
		public static bool EventFiringDisabled
		{
			get { return GetEventFiringSwitchValue(); }
		}

		private static Type EventManagerType
		{
			get
			{
				if (_eventManagerType == null)
					GetEventManagerType();

				return _eventManagerType;
			}
		}

		/// <summary>
		/// enables event firing on the current thread
		/// </summary>
		public static void EnableEventFiring()
		{
			SetEventFiringSwitch(false);
		}

		/// <summary>
		/// disables sharepoint event firing on the current thread
		/// </summary>
		public static void DisableEventFiring()
		{
			SetEventFiringSwitch(true);
		}

		/// <summary>
		/// sets the event firing switch on Microsoft.SharePoint.SPEventManager class using reflection
		/// </summary>
		/// <param name="value"></param>
		private static void SetEventFiringSwitch(bool value)
		{
			PropertyInfo pi = EventManagerType.GetProperty(EventFiringSwitchName, BindingFlags.Static | BindingFlags.NonPublic);
			pi.SetValue(null, value, null);
		}

		private static bool GetEventFiringSwitchValue()
		{
			PropertyInfo pi = EventManagerType.GetProperty(EventFiringSwitchName, BindingFlags.Static | BindingFlags.NonPublic);
			object val = pi.GetValue(null, null);
			return (bool)val;
		}

		private static void GetEventManagerType()
		{
			_eventManagerType = typeof(SPList).Assembly.GetType(ClassName, true);
			return;
		}
	}
}